﻿var map, infobox, dataLayer, sessionKey;
var trafficTypes = [null, "Accident", "Congestion", "Disabled Vehicle", "Mass Transit", "Miscellaneous", "Other News", "Planned Event", "Road Hazard", "Construction", "Alert", "Weather"];

function GetMap() {
    // Initialize the map
    map = new Microsoft.Maps.Map(document.getElementById("myMap"), {
        credentials: "YOUR_BING_MAPS_KEY",
        center: new Microsoft.Maps.Location(51.5, 0),
        zoom: 10
    });

    //Add a layer for pushpin data
    dataLayer = new Microsoft.Maps.EntityCollection();
    map.entities.push(dataLayer);

    //Add a layer for the infobox
    var infoboxLayer = new Microsoft.Maps.EntityCollection();
    map.entities.push(infoboxLayer);

    //Create a global infobox control
    infobox = new Microsoft.Maps.Infobox(new Microsoft.Maps.Location(0, 0), {
        visible: false,
        offset: new Microsoft.Maps.Point(0, 20),
        height: 150,
        width: 300
    });
    infoboxLayer.push(infobox);

    map.getCredentials(function (c) {
        sessionKey = c;

        //Use a throttled event to reduce the number of unwanted events being fired.
        Microsoft.Maps.Events.addThrottledHandler(map, 'viewchangeend', MakePOIRequest, 250);

        //Make a request as the map to initially fill the map
        MakePOIRequest();
    });    
}

function MakePOIRequest() {
    var bbox = map.getBounds();

    //Create the request to the traffic incidents service.
    var poiRequest = "http://dev.virtualearth.net/REST/v1/Traffic/Incidents/" +
        bbox.getSouth() + "," + bbox.getWest() + "," + bbox.getNorth() + "," +
        bbox.getEast() + "?key=" + sessionKey;

    //Process the request and fire the callback
    WinJS.xhr({ url: poiRequest }).then(POICallback);
}

function POICallback(response) {
    dataLayer.clear();
    infobox.setOptions({ visible: false });

    if (response.status == 200) {
        //Parse JSON response
        var result = JSON.parse(response.responseText);

        if (result != null &&
            result.resourceSets != null &&
			result.resourceSets.length > 0 &&
            result.resourceSets[0].resources != null &&
            result.resourceSets[0].resources.length > 0) {
            var r = result.resourceSets[0].resources;

            //add the POI data to the map
            for (var i = 0; i < r.length; i++) {
                //Get coordinate of incident
                var location = new Microsoft.Maps.Location(r[i].point.coordinates[0], r[i].point.coordinates[1]);

                //Get custom icon based on severity
                var customIcon = '/images/';

                switch (r[i].severity) {
                    case 2: //Minor
                        customIcon += 'yellow_pin.png';
                        break;
                    case 3: //Moderate
                        customIcon += 'red_pin.png';
                        break;
                    case 4: //Serious
                        customIcon += 'black_pin.png';
                        break;
                    case 1: //Low Impact
                    default:
                        customIcon += 'green_pin.png';
                        break;
                }
                               
                //Create a pushpin for the incident
                var pushpin = new Microsoft.Maps.Pushpin(location, { icon: customIcon });

                pushpin.Title = trafficTypes[r[i].type];

                //Generate the description HTML markup
                pushpin.Description = "<b>Last Update:</b> " + parseJsonDate(r[i].lastModified) +
                        '<br/><br/><b>Description:</b> ' + trafficTypes[r[i].type] + " " + r[i].description;

                //Add a click event to the pushpin
                Microsoft.Maps.Events.addHandler(pushpin, 'click', displayInfobox);

                //Add the pushpin to the data layer
                dataLayer.push(pushpin);
            }
        }
    }
}

function displayInfobox(e) {
    if (e.targetType == 'pushpin') {
        infobox.setLocation(e.target.getLocation());
        infobox.setOptions({ visible: true, title: e.target.Title, description: e.target.Description });
    }
}

/******** Common Functions ********/

function parseJsonDate(jsonDate) {
    var offset = new Date().getTimezoneOffset();
    var parts = /\/Date\((-?\d+)([+-]\d{2})?(\d{2})?.*/.exec(jsonDate);

    if (parts[2] == undefined)
        parts[2] = 0;

    if (parts[3] == undefined)
        parts[3] = 0;

    return new Date(+parts[1] + offset + parts[2] * 3600000 + parts[3] * 60000);
}

//Initialization logic for loading the map control
(function () {
    function initialize() {
        Microsoft.Maps.loadModule('Microsoft.Maps.Map', { callback: GetMap });
    }

    document.addEventListener("DOMContentLoaded", initialize, false);
})();